package com.jinzhi.jzweb.controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.jinzhi.common.annotation.Log;
import com.jinzhi.common.base.BaseController;
import com.jinzhi.common.domain.DictDO;
import com.jinzhi.common.service.DictService;
import com.jinzhi.common.utils.Result;
import com.jinzhi.jzapi.utils.ExcelStyleUtil;
import com.jinzhi.jzweb.domain.*;
import com.jinzhi.jzweb.pojo.EmploymentUnitVo;
import com.jinzhi.jzweb.pojo.ExportPointsVo;
import com.jinzhi.jzweb.pojo.ExportStatisticsVo;
import com.jinzhi.jzweb.service.*;
import com.jinzhi.jzweb.utils.WithZoreUtil;
import com.jinzhi.sys.domain.RoleDO;
import com.jinzhi.sys.domain.UserDO;
import com.jinzhi.sys.domain.UserRoleDO;
import com.jinzhi.sys.service.RoleService;
import com.jinzhi.sys.service.UserRoleService;
import com.jinzhi.sys.service.UserService;
import net.sf.json.JSONArray;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 
 * <pre>
 * 机构角色表
 * </pre>
 * <small> 2020-02-24 21:00:11 | lance</small>
 */
@Controller
@RequestMapping("/jzweb/organizationRoles")
public class OrganizationRolesController extends BaseController {
	@Autowired
	private OrganizationRolesService organizationRolesService;
	@Autowired
	private CertificateProfileService certificateProfileService;
	@Autowired
	private UserService userService;
	@Autowired
	private OrganizationNewsService organizationNewsService;
	@Autowired
	private RoleService roleService;
	@Autowired
	private UserRoleService userRoleService;
	@Autowired
	private DictService dictService;
	@Autowired
	private MsgService msgService;
	@Autowired
	private OrgRelationService orgRelationService;

	@GetMapping()
	@RequiresPermissions("jzweb:organizationRoles:organizationRoles")
	String OrganizationRoles(){
	    return "jzweb/organizationRoles/organizationRoles";
	}
	
	@ResponseBody
	@GetMapping("/list")
	@RequiresPermissions("jzweb:organizationRoles:organizationRoles")
	public Result<Page<OrganizationRolesDO>> list(OrganizationRolesDO organizationRolesDTO){
		Wrapper<OrganizationRolesDO> wrapper = new EntityWrapper<OrganizationRolesDO>().orderBy("id", false);
		wrapper.notIn("checker_state" , 4);
		if (organizationRolesDTO.getRoleType() != null){
			wrapper.eq("role_type",organizationRolesDTO.getRoleType());
		}
		if (organizationRolesDTO.getCheckerState() != null){
			wrapper.eq("checker_state",organizationRolesDTO.getCheckerState());
		}
		if (StringUtils.isNotBlank(organizationRolesDTO.getOrgName())){
			Wrapper<OrganizationNewsDO> orWrapper = new EntityWrapper<OrganizationNewsDO>().like("name",organizationRolesDTO.getOrgName());
			List<OrganizationNewsDO>  organizationNewsDOS = organizationNewsService.selectList(orWrapper);
			String str = "";
			for (OrganizationNewsDO organizationNewsDO : organizationNewsDOS){
				str = str + organizationNewsDO.getId() + ",";
			}
			wrapper.and();
			if(StringUtils.isNotBlank(str)){
				wrapper.in("org_id",str.substring(0,str.length()-1));
			}else{
				wrapper.eq("org_id",null);
			}
		}

		Page<OrganizationRolesDO> page = organizationRolesService.selectPage(getPage(OrganizationRolesDO.class), wrapper);
		List list = new ArrayList();
		for (int i = 0; i < page.getRecords().size(); i++) {
			OrganizationRolesDO obj = (OrganizationRolesDO) page.getRecords().get(i);
			if (obj.getCheckerId() != null){
				UserDO userDO = userService.selectById(obj.getCheckerId());
				if (userDO != null) {
					obj.setCheckerName(userDO.getUsername());
				}
			}
			if (obj.getApplicantId() != null){
				UserDO userDO = userService.selectById(obj.getApplicantId());
				if (userDO != null) {
					if(StringUtils.isNotBlank(userDO.getName())){
						obj.setApplicantName(userDO.getName());
					}else{
						obj.setApplicantName(userDO.getUsername());
					}

				}
			}
			if (StringUtils.isNotBlank(obj.getProfileId())){
				String[] profilesId = obj.getProfileId().split(",");
				String returnK = null;
					for(int j = 0;j<profilesId.length;j++){
						if(profilesId[j] != "" && profilesId[j] != null){
							CertificateProfileDO certificateProfileDO = certificateProfileService.selectById(Long.parseLong(profilesId[j]));
							if (certificateProfileDO != null) {
								if(returnK == null){
									returnK = certificateProfileDO.getName();
								}else{
									returnK = returnK + "," + certificateProfileDO.getName();
								}
							}
						}
					}

				obj.setProfileName(returnK);
			}
			if (obj.getOrgId() != null){
				OrganizationNewsDO organizationNewsDO = organizationNewsService.selectById(obj.getOrgId());
				if (organizationNewsDO != null) {
					obj.setOrgName(organizationNewsDO.getName());
				}
			}
			list.add(obj);
		}
		page.setRecords(list);
        return Result.ok(page);
	}
	
	@GetMapping("/add")
	@RequiresPermissions("jzweb:organizationRoles:add")
	String add(Model model){
		model.addAttribute("organizationNews",organizationNewsService.selByOrgId());
	    return "jzweb/organizationRoles/add";
	}

	@GetMapping("/edit/{id}")
	@RequiresPermissions("jzweb:organizationRoles:edit")
	String edit(@PathVariable("id") Long id,Model model){
		model.addAttribute("organizationNews",organizationNewsService.selByOrgId());
		OrganizationRolesDO organizationRoles = organizationRolesService.selectById(id);
		model.addAttribute("organizationRoles", organizationRoles);
	    return "jzweb/organizationRoles/edit";
	}
	
	@Log("添加机构角色表")
	@ResponseBody
	@PostMapping("/save")
	@RequiresPermissions("jzweb:organizationRoles:add")
	public Result<String> save( OrganizationRolesDO organizationRoles){
		/*取机构信息表里的负责人id放入角色表的申请人id*/
		OrganizationNewsDO organizationNewsDO =  organizationNewsService.selectById(organizationRoles.getOrgId());
		organizationRoles.setApplicantId(organizationNewsDO.getLeadingCadreId());

		organizationRoles.setApplicantDate(new Date());
		organizationRolesService.insert(organizationRoles);
        return Result.ok();
	}
	
	@Log("修改机构角色表")
	@ResponseBody
	@RequestMapping("/update")
	@RequiresPermissions("jzweb:organizationRoles:edit")
	public Result<String>  update( OrganizationRolesDO organizationRoles){
		boolean update = organizationRolesService.updateById(organizationRoles);
		return update ? Result.ok() : Result.fail();
	}
	
	@Log("删除机构角色表")
	@PostMapping( "/remove")
	@ResponseBody
	@RequiresPermissions("jzweb:organizationRoles:remove")
	public Result<String>  remove( Long id){
		OrganizationRolesDO oldOrgs = organizationRolesService.selectById(id);
		//删除原本的角色权限，重新审核后赋权；
		delRoleOrg(oldOrgs.getRoleType(),oldOrgs.getApplicantId());
		organizationRolesService.deleteById(id);
        return Result.ok();
	}
	
	@Log("批量删除机构角色表")
	@PostMapping( "/batchRemove")
	@ResponseBody
	@RequiresPermissions("jzweb:organizationRoles:batchRemove")
	public Result<String>  remove(@RequestParam("ids[]") Long[] ids){
		for(Long id : ids){
			OrganizationRolesDO oldOrgs = organizationRolesService.selectById(id);
			//删除原本的角色权限，重新审核后赋权；
			delRoleOrg(oldOrgs.getRoleType(),oldOrgs.getApplicantId());
		}

		organizationRolesService.deleteBatchIds(Arrays.asList(ids));
		return Result.ok();
	}

	@Log("导出考核点汇总信息")
	@GetMapping("/exportStatistics")
	@ResponseBody
	@Transactional
	@RequiresPermissions("jzweb:organizationRoles:import")
	public void exportStatistics(HttpServletRequest request, HttpServletResponse response,String state , String batchTime) throws Exception {
		// 告诉浏览器用什么软件可以打开此文件
		response.setHeader("content-Type", "application/vnd.ms-excel");
		// 下载文件的默认名称
		response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("考核点信息汇总表", "UTF-8") + ".xls");
		//编码
		response.setCharacterEncoding("UTF-8");

		String startDate = null;
		String endDate = null;
		if (batchTime != null && !batchTime.equals("")){ //b.substring(0, b.indexOf("-"));  //b.substring(b.indexOf("-")+1);
			startDate = batchTime.substring(0 ,batchTime.indexOf("/"))+" 00:00:00";
			endDate =  batchTime.substring(batchTime.indexOf("/")+1)+" 23:59:59";
		}

		//获取信息集合成一个信息list
		Map map = new HashMap();
		map.put("cState",state);
		map.put("startDate" ,startDate);
		map.put("endDate" , endDate);
		List<ExportStatisticsVo> groupList = organizationNewsService.selOrgExportStaList(map);
		if(groupList != null && groupList.size() > 0){
			for(int ss=0;ss<groupList.size();ss++){
				//考评团队规模（人）
				if(StringUtils.isNotBlank(groupList.get(ss).getTeamSize())){
					JSONArray jsonArray = JSONArray.fromObject(groupList.get(ss).getTeamSize());
					if(jsonArray != null){
						groupList.get(ss).setTeamSize(String.valueOf(jsonArray.size()));
					}else{
						groupList.get(ss).setTeamSize("0");
					}
				}else{
					groupList.get(ss).setTeamSize("0");
				}
				//场地设备总量（套）
				if(StringUtils.isNotBlank(groupList.get(ss).getTotalEquipment())){
					JSONArray jsonArray = JSONArray.fromObject(groupList.get(ss).getTotalEquipment());
					if(jsonArray != null){
						groupList.get(ss).setTotalEquipment(String.valueOf(jsonArray.size()));
					}else{
						groupList.get(ss).setTotalEquipment("0");
					}
				}else{
					groupList.get(ss).setTotalEquipment("0");
				}
				//实习就业单位数（个）
				if(StringUtils.isNotBlank(groupList.get(ss).getInternshipNumber())){
					JSONArray jsonArray = JSONArray.fromObject(groupList.get(ss).getInternshipNumber());
					if(jsonArray != null){
						groupList.get(ss).setInternshipNumber(String.valueOf(jsonArray.size()));
					}else{
						groupList.get(ss).setInternshipNumber("0");
					}
				}else{
					groupList.get(ss).setInternshipNumber("0");
				}

			}
		}

		//调用导出方法
		Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams(), ExportStatisticsVo.class, groupList);
		workbook.write(response.getOutputStream());
	}



	@Log("导出考核点对应的实习就业单位信息")
	@GetMapping("/exportPoints")
	@ResponseBody
	@Transactional
	@RequiresPermissions("jzweb:organizationRoles:import")
	public void exportPoints(HttpServletRequest request, HttpServletResponse response,String state) throws Exception {
		// 告诉浏览器用什么软件可以打开此文件
		response.setHeader("content-Type", "application/vnd.ms-excel");
		// 下载文件的默认名称
		response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("实习就业单位详情表", "UTF-8") + ".xls");
		//编码
		response.setCharacterEncoding("UTF-8");
		//获取信息集合成一个信息list
		Map map = new HashMap();
		map.put("cState",state);
		List<Map> groupList = organizationNewsService.selOrgExportUnit(map);
		List<ExportPointsVo> exportPointsVos = new ArrayList<>();
		if(groupList != null && groupList.size() > 0){
			for(int ss=0;ss<groupList.size();ss++){
				ExportPointsVo exportPointsVo = new ExportPointsVo();
				if(groupList.get(ss).get("name") != null){
					exportPointsVo.setName(groupList.get(ss).get("name").toString());
				}
				if(groupList.get(ss).get("orgName") != null){
					exportPointsVo.setOrgName(groupList.get(ss).get("orgName").toString());
				}
				if(groupList.get(ss).get("checkerState") != null){
					exportPointsVo.setCheckerState(groupList.get(ss).get("checkerState").toString());
				}
				//实习就业详情
				if(groupList.get(ss).get("internshipNumber") != null){
					JSONArray jsonArray = JSONArray.fromObject(groupList.get(ss).get("internshipNumber"));
					if(jsonArray != null){
						List<EmploymentUnitVo> employmentUnitVos = new ArrayList<>();
						for(int i = 0;i<jsonArray.size();i++){
							EmploymentUnitVo employmentUnitVo = new EmploymentUnitVo();
							employmentUnitVo.setDwName(jsonArray.getJSONObject(i).getString("dwName"));
							employmentUnitVo.setDwUser(jsonArray.getJSONObject(i).getString("dwUser"));
							employmentUnitVo.setDwMobile(jsonArray.getJSONObject(i).getString("dwMobile"));
							employmentUnitVo.setJyUser(jsonArray.getJSONObject(i).getString("jyUser"));
							employmentUnitVo.setJyMobile(jsonArray.getJSONObject(i).getString("jyMobile"));
							employmentUnitVo.setZpNum(jsonArray.getJSONObject(i).getString("zpNum"));
							employmentUnitVo.setZpPost(jsonArray.getJSONObject(i).getString("zpPost"));
							employmentUnitVo.setEmolument(jsonArray.getJSONObject(i).getString("emolument"));
							employmentUnitVos.add(employmentUnitVo);
						}
						exportPointsVo.setEmployer(employmentUnitVos);
					}
				}
				exportPointsVos.add(exportPointsVo);
			}
		}

		//调用导出方法
		ExportParams exportParams = new ExportParams("实习就业单位详情", "实习就业单位详情", ExcelType.XSSF);
		exportParams.setStyle(ExcelStyleUtil.class);
		Workbook workbook = ExcelExportUtil.exportExcel(exportParams,ExportPointsVo.class, exportPointsVos);
		workbook.write(response.getOutputStream());
	}

	boolean delRoleOrg(Integer type,Long userId) {
		boolean b = true;
		//给会员赋予相应角色权限
		String roleNames = null;
		if(type.equals(0)){
			roleNames = "培训机构";
		}else if(type.equals(1)){
			roleNames = "实训基地";
		}else if(type.equals(2)){
			roleNames = "考评站";
		}else if(type.equals(3)){
			roleNames = "实习就业单位";
		}else if(type.equals(4)){
			roleNames = "培训考试点";
		}else if(type.equals(5)){
			roleNames = "考核站点";
		}
		if (roleNames != null) {
			RoleDO roleDO = roleService.findOneByKv("roleName", roleNames);

			//查询用户角色
			UserRoleDO userRole = userRoleService.findOneByKv("userId", userId,"roleId",roleDO.getId());
			if(userRole != null){
				b = userRoleService.deleteById(userRole.getId());
			}
		}

		return b;
	}

	@Log("审核")
	@PostMapping( "/review")
	@ResponseBody
	@RequiresPermissions("jzweb:organizationRoles:review")
	public Result<String>  review(@RequestParam("ids[]") Long[] ids,Integer state,String remark){
		if (state.equals(2) || state.equals(1)) {

			//查询字典:消息模板
			DictDO dic = null;
			String valStr = "";
			SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			if (state == 2){
				dic = dictService.findOneByKv("type" , "check_no_pass");
				valStr = dic.getValue().replace("{value4}" , remark);
			}else {
				dic = dictService.findOneByKv("type" , "check_pass");
				valStr = dic.getValue();
			}
			valStr =  valStr.replace("{value1}" , "机构信息");
			valStr = valStr.replace("{value2}" , this.getUser().getUsername());
			valStr = valStr.replace("{value3}" , formatter.format(new Date()));

			int i = 0;
			for (Long id : ids) {
				OrganizationRolesDO organizationRolesDO = organizationRolesService.selectById(id);

				if(organizationRolesDO != null){
					organizationRolesDO.setCheckerState(state);
					organizationRolesDO.setCheckerId(this.getUserId());
					organizationRolesDO.setCheckerDate(new Date());

					//添加消息
					MsgDO msg = new MsgDO();
					if(state.equals(2)){
						organizationRolesDO.setRemark(remark);//未通过，添加备注

						msg.setTitle("机构信息审核未通过！");
					}else{
						organizationRolesDO.setRemark("");//审核通过，清空备注
						msg.setTitle("机构信息审核通过！");
					}
					boolean b = organizationRolesService.updateById(organizationRolesDO);
					if (b) {
						OrganizationNewsDO organizationNews = organizationNewsService.selectById(organizationRolesDO.getOrgId());
						msg.setContent(valStr);
						msg.setUserId(organizationNews.getLeadingCadreId());
						msg.setCreaterDate(new Date());
//						msg.setEnclosure();
						msg.setType(0);
						msg.setMsgType(0);
						msg.setState(0);
						msg.setCreaterId(this.getUserId());
						msgService.insert(msg);

						if(state.equals(1)){
							//当机构角色为考核站点且审核通过后，判断该机构是否有系统的考点编号，如没有，则新增一个，分配考试时调用
							if(organizationRolesDO.getRoleType().equals(5) && organizationRolesDO.getCheckerState().equals(1)){
								OrganizationNewsDO organizationNewsDO = organizationNewsService.selectById(organizationRolesDO.getOrgId());
								if(organizationNewsDO != null){
									//todo 查询实习单位与机构关联表
									//根据考核点负责人查询关联表的机构负责人
									List<OrgRelationDO> orgRelationList = orgRelationService.findByKv("org_user_id" ,organizationRolesDO.getApplicantId());
									for (OrgRelationDO orgRelation : orgRelationList){
										orgRelation.setOrgId(organizationNewsDO.getId());
										orgRelationService.updateById(orgRelation);
										//根据实习机构id查询机构表信息
										OrganizationNewsDO orgNews = organizationNewsService.selectById(orgRelation.getCorrelationOrgId());
										if (orgNews != null){
											//根据机构负责人id查询是否有用户信息，有
											if (orgNews.getLeadingCadreId() != null){
												UserDO user = userService.selectById(orgNews.getLeadingCadreId());
												if (user != null){//自动生成
													organizationNewsDO.setImportActivateNum(organizationNewsDO.getImportActivateNum()+1);
												}
											}
										}else {
											return Result.fail("关联实习单位机构信息不存在！");
										}
									}
									organizationNews.setTrainingOrgNum(orgRelationList.size());
									organizationNewsDO.setNumberOfExaminees(organizationNewsDO.getNumberOfExaminees());
									organizationNewsService.updateById(organizationNews);

									if(StringUtils.isBlank(organizationNews.getOrgNum())){
										Integer maxOrgNum = organizationNewsService.selMaxOrgNum();
										//单数字转成01格式
										String ccs = WithZoreUtil.frontCompWithZore((maxOrgNum+1),3);
										organizationNewsDO.setOrgNum(ccs);
										boolean c = organizationNewsService.updateById(organizationNewsDO);
										if(!c){
											i--;
										}
									}
								}
							}

							//给会员赋予相应角色权限
							String roleNames = null;
							if(organizationRolesDO.getRoleType().equals(0)){
								roleNames = "培训机构";
							}else if(organizationRolesDO.getRoleType().equals(1)){
								roleNames = "实训基地";
							}else if(organizationRolesDO.getRoleType().equals(2)){
								roleNames = "考评站";
							}else if(organizationRolesDO.getRoleType().equals(3)){
								roleNames = "实习就业单位";
							}else if(organizationRolesDO.getRoleType().equals(4)){
								roleNames = "培训考试点";
							}else if(organizationRolesDO.getRoleType().equals(5)){
								roleNames = "考核站点";
							}
							if(roleNames != null){
								RoleDO roleDO = roleService.findOneByKv("roleName",roleNames);

								List<RoleDO> roleDOS = roleService.findListByUserId(organizationRolesDO.getApplicantId());
								if(roleDOS != null && roleDOS.size() > 0){
									List<String> roleNamess = new ArrayList<>();
									for(RoleDO roleDO1:roleDOS){
										roleNamess.add(roleDO1.getRoleName());
									}
									//当前列表若包含该角色，返回结果为true, 若不包含该角色，返回结果为false。
									if (!(roleNamess.indexOf(roleNames) > -1)) {

										if(roleDO != null){
											UserRoleDO userRoleDO = new UserRoleDO();
											userRoleDO.setUserId(organizationRolesDO.getApplicantId());
											userRoleDO.setRoleId(roleDO.getId());
											boolean c = userRoleService.insert(userRoleDO);
											if(!c){
												i--;
											}
										}
									}
								}else{
									if(roleDO != null){
										UserRoleDO userRoleDO = new UserRoleDO();
										userRoleDO.setUserId(organizationRolesDO.getApplicantId());
										userRoleDO.setRoleId(roleDO.getId());
										boolean c = userRoleService.insert(userRoleDO);
										if(!c){
											i--;
										}
									}
								}
							}

							//修改申请人用户类型
							UserDO userDO = userService.selectById(organizationRolesDO.getApplicantId());
							OrganizationNewsDO organizationNewsDO = organizationNewsService.selectById(organizationRolesDO.getOrgId());
							if(organizationNewsDO != null){

								if (userDO.getOrgId() == null){
									userDO.setOrgId(organizationNewsDO.getId());
									userDO.setOrgName(organizationNewsDO.getName());
								}
							}
							userDO.setType(1);
							boolean c = userService.updateById(userDO);
							if(!c){
								i--;
							}
						}

						i++;
					} else {
						break;
					}
				}
			}
			if (i == ids.length) {
				return Result.build(0,"已成功审核：" + i + "条数据");
			} else {
				return Result.fail("审核状态修改失败！");
			}
		} else {
			return Result.fail("审核状态修改失败！");
		}
	}
}
